package Country;
import java.util.Collection;
import java.util.Iterator;
import java.util.TreeMap;

class myKey implements Comparable{//定义一个myKey类，用于实现Comparable接口
    long COVID19;//定义一个成员变量

    public myKey(long c){//构造方法，用于初始化COVID19变量
        COVID19 = c;
    }

    public int compareTo(Object o){//重写CompareTO()方法 - 用于排序
        myKey k = (myKey) o;//将Object对象强制类型转换为myKey，并赋给k
        if(this.COVID19==k.COVID19){
            return 1;
        }else {
            return (int)(this.COVID19-k.COVID19);
        }
    }
}

public class TestComparable {
    public static void main(String[] args) {
        //定义一个countries数组，用于存放10个实例化的Country对象
        Country[] countries = new Country[10];
        //将10个国家的信息放到countries数组中
        countries[0] = new Country("美国",20932750,44918565);
        countries[1] = new Country("中华人民共和国",14722837,124924);
        countries[2] = new Country("日本",5048688,1706675);
        countries[3] = new Country("德国",3803014,4284354);
        countries[4] = new Country("英国",2710970,8006660);
        countries[5] = new Country("印度",2708770,33893002);
        countries[6] = new Country("法国",2598907,7038701);
        countries[7] = new Country("意大利",1884935,4689341);
        countries[8] = new Country("加拿大",1643408,1647142);
        countries[9] = new Country("韩国",1630871,323379);

        //创建一个TreeMap的对象treeMap,其中myKey作为treeMap的键，使treeMap中的元素按照myKey排序
        TreeMap<myKey,Country> treeMap = new TreeMap<myKey, Country>();

        //循环调用put()方法将myKey/Country数据对存放到treeMap中
        for (int i = 0; i < countries.length; i++) {
            treeMap.put(new myKey(countries[i].COVID19),countries[i]);
        }

        //调用values()方法将treeMap中的值-country放到集合collection中。
        Collection<Country> collection = treeMap.values();

        //利用迭代器遍历集合中的元素，并依次将元素输出
        Iterator<Country> iterator = collection.iterator();//创建一个迭代器iterator

        System.out.println("按照新冠累计确诊人数从小到大输出以下10个国家信息：");
        while(iterator.hasNext()){//调用hasNext()方法检查迭代器中是否还有元素
            Country c = iterator.next();//调用next()方法将迭代器中的下一元素放到一个Country对象c中
            System.out.println(c);//输出c
        }

    }
}
